package it.antonio.ilpizze.ioc;


public class IocContainer {
	
	private Dependencies dependencies;
	
	private IocContainer() {
		this.dependencies = new Dependencies();
	}

	public static IocContainer create(Module... modules){
		IocContainer container = new IocContainer();
		for(Module module: modules) module.contribute(container.dependencies);
		return container;
	} 
	public static IocContainer create(Iterable<Module> modules){
		IocContainer container = new IocContainer();
		for(Module module: modules) module.contribute(container.dependencies);
		return container;
	} 
	
	
	public <T> T get(Object key) {
		try{
			return dependencies.get(key);
		} catch(IocSignalException e) {
			if(e.getDelegate() instanceof RuntimeException){
				throw (RuntimeException) e.getDelegate();
			}
			throw new IocException(e.getDelegate().getMessage(), e.getDelegate());
		}
	}

	public void decorate(Object instance) {
		try{
			dependencies.decorate(instance);
		} catch(IocSignalException e) {
			if(e.getDelegate() instanceof RuntimeException){
				throw (RuntimeException) e.getDelegate();
			}
			throw new IocException(e.getDelegate().getMessage(), e.getDelegate());
		}
	}
		
}
